<template>
  <div class="map-container" id="mapcontainer"></div>
</template>

<script setup lang="ts" name="Map">
import { ref, watch, onMounted, shallowRef } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const props = defineProps({
  dataList: {
    type: Array,
    default: () => []
  }
})
let AMap = null as any
const map = shallowRef<any>(null)
const layer = shallowRef<any>(null)
const points = ref<Array<any>>([])
const markers = [] as any
onMounted(async () => {
  AMap = await initializeMap()
  map.value = new AMap.Map('mapcontainer', {
    viewMode: '2D',
    zoom: 0,
    center: [105.602725, 37.076636],
    mapStyle: 'amap://styles/normal'
  })
  layer.value = new AMap.LabelsLayer({
    zooms: [0, 20],
    zIndex: 1000,
    collision: false,
    allowCollision: false
  })
  map.value.add(layer.value)
  if (points.value.length) {
    renderMarkers()
  }
})

function initializeMap (): Promise<any> {
  return new Promise((resolve, reject) => {
    AMapLoader.load({
      key: '9234dcb503af575b38e158c6e3f2aae2',
      version: '2.0',
      plugins: ['']
    }).then(AMap => {
      resolve(AMap)
    }).catch(error => {
      reject(error)
    })
  })
}

function renderMarkers () {
  points.value.forEach((p: any) => {
    const icon = {
      type: 'image',
      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
      size: [6, 9],
      anchor: 'bottom-center'
    }
    const curData = {
      position: p.lonlat.split(',').reverse(),
      icon
    }
    const labelMarker = new AMap.LabelMarker(curData)
    markers.push(labelMarker)
  })
  layer.value.add(markers)
  map.value.setFitView()
}

watch(() => props.dataList, val => {
  if (val?.length) {
    points.value = val
    if (map.value) {
      renderMarkers()
    }
  }
})
</script>

<style lang="scss">
.map-container {
  width: 100%;
  height: 100%;
  .amap-logo, .amap-copyright {
    display: none !important;
  }
}
</style>
